<?php
/**
 * 默认的index模块下的默认的controller
 */
class Controller_Index extends Controller_Base{
	public function action_index($data=array()){
		//最热投票
		$hots = new Model_Base('fg__vote',array('Id>?'=>0),'Id,Name,VoteNum','VoteNum desc',1,10);
		$lasts = new Model_Base('fg__vote',array('Id>?'=>0),'Id,Name,VoteNum,CreateTime','CreateTime desc',1,10);
		$set = array('title'=>'投票系统--本系统仅作为笔试题目作品','hots'=>$hots->stack(),'lasts'=>$lasts->stack());
		unset($hots);unset($lasts);
		$set = array_merge($set,$data);
		$this->bind($set)->view()->show();
	}

	public function action_reg(){
		$username = t::post('username','');
		$email = t::post('email','');
		$password = t::post('password','');
		$err_arr = array();
		
		if(!preg_match("/^[\x{4e00}-\x{9fa5}A-Za-z0-9_]{2,10}$/u", $username)){
			$err_arr []= "用户名限制为2~10个中英文\数字\下划线!";
		}else{
			$hasone = new Model_Base('fg__user',array('Name'=>$username),'Id');
			//var_dump($hasone->v('Id'));
			if($hasone->v('Id')){
				$err_arr []= "用户名已存在!";
			}
			unset($hasone);
		}
		
		if(!preg_match("/^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/i", $email)){
			$err_arr []= "邮箱格式似乎不正确!";
			$hasone = new Model_Base('fg__user',array('Email'=>$email),'Id');
			//var_dump($hasone->v('Id'));
			if($hasone->v('Id')){
				$err_arr []= "邮箱已存在!";
			}
			unset($hasone);
		}
		
		if(!preg_match("/^[A-Za-z0-9_]{6,16}$/u", $password)){
			$err_arr []= "密码应为6-16为英文\数字\下划线!";
		}
		
		if($err_arr){	//有错误
			$this->json(array('succeed'=>0,'msg'=>implode("<br/>", $err_arr)));
		}
		
		//注册新用户
		$m = new Model_Base('fg__user');
		$m->v('Name',$username)
			->v('Email',$email)
			->v('Pwd',md5($username.$email.md5($password)))
			->v('LastIp',ip2long(t::get_ip()))
			->v('CreateTime',time());
		$res = $m->insert();
		if($res){
			$this->json(array('succeed'=>1,'data'=>$res));
		}else{
			$this->json(array('succeed'=>0,'msg'=>"注册失败,请重试!"));
		}
	}
	
	
	public function action_login(){
		$username = t::post('username','');
		$password = t::post('password','');
		$err_arr = array();
		if(trim($username == '')){
			$err_arr []= "用户名或Email不能为空哦~";
		}
		if(trim($password == '')){
			$err_arr []= "密码不能为空哦~";
		}
		if($err_arr){	//有错误
			$this->json(array('succeed'=>0,'msg'=>implode("<br/>", $err_arr)));
		}

		$user = new Model_Base('fg__user',array('`Name`=? or `Email`=?'=>array($username,$username)),'*');
		if($user->v('Id')){
			if(md5($user->v('Name').$user->v('Email').md5($password)) == $user->v('Pwd')){	//校验密码
				$_SESSION['uid'] = $user->v('Id');
				$_SESSION['user'] = $user->getParam();
				$this->json(array('succeed'=>1));
			}else{
				$this->json(array('succeed'=>0,'msg'=>"密码错误!"));
			}
		}else{
			$this->json(array('succeed'=>0,'msg'=>"不存在此账户,请检查!"));
		}		
	}
	
	public function action_logout(){
		session_unset();
		session_destroy();
		$this->action_index();
	}
}